import axios from 'axios'
import {ElMessage} from 'element-plus'
import {useLoadingStore} from '@/stores/counter'
import VueCookie from 'vue-cookie'
import router from "@/router/index.js";
import {fetchUser} from "@/components/userInfo.js";

const _axios = axios.create({
    baseURL: 'http://localhost:8081'
})

_axios.interceptors.request.use(config => {
    const token = VueCookie.get('sessionId')
    if (token) {
        config.headers.token = token
    }
    return config
})

export const request = (url, method, data, callback) => {
    const loadingStore = useLoadingStore()
    const axios_config = {
        url,
        method
    }
    if (method === 'post') {
        const formData = new FormData()
        for (const key in data) {
            if (data[key] instanceof Array) {
                for (const i in data[key]) {
                    formData.append(key, data[key][i])
                }
            } else {
                formData.append(key, data[key])
            }
        }

        axios_config.data = formData
    } else {
        axios_config.params = data
    }
    loadingStore.open()
    _axios.request(axios_config).then(response => {
        console.log(axios_config)
        if (response.data.code === 200) {
            if (response.data.message) {
                ElMessage.success(response.data.message)
            }
            callback(response.data.content)
        } else {
            ElMessage.error(response.data.message)
            if (response.data.code === 401) {
                router.push('/login')
            }
        }
    }).catch(error => {
        ElMessage.error(error.message)
    }).finally(() => {
        loadingStore.close()
    })
}
export const get = (url, data, callback) => {
    request(url, 'get', data, callback)
}
export const post = (url, data, callback, formObj = null) => {
    if (formObj) {
        formObj.validate(valid => {
            if (valid) {
                request(url, 'post', data, callback)
                return true
            }
        })
    } else {
        request(url, 'post', data, callback)
        return true
    }
}